package com.bbs.ptc.common;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.ParameterizedType;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.bbs.ptc.model.system.Syslog;
import com.bbs.ptc.tools.ToolString;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;

/**
 * @author JiaYongChao
 *
 * @param <T>
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public abstract class  BaseController<T>  extends Controller {
	private static Logger log = Logger.getLogger(BaseController.class);
	/**
	 * 全局变量
	 */
	protected String ids;			// 主键
	protected List<?> list;			// 公共list
	protected Syslog reqSysLog;		// 访问日志
	/**
	 * 获取项目请求根路径
	 * @return
	 */
	protected String getCxt() {
		return getAttr("cxt");
	}
	
	/**
	 * 重写getPara，进行二次decode解码
	 */
	@Override
	public String getPara(String name) {
		String value = getRequest().getParameter(name);
		if(null != value && !value.isEmpty()){
			try {
				value = URLDecoder.decode(value, ToolString.encoding);
			} catch (UnsupportedEncodingException e) {
				log.error("decode异常："+value);
			}
		}
		return value;
	}

	//@formatter:off 
	/**
	 * Title: getModel
	 * Description:
	 * Created On: 2014年9月4日 下午3:39:22
	 * @author JiaYongChao
	 * <p>
	 * @return 
	 */
	//@formatter:on
	public T getModel()
	{
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
		Class modelClass = (Class) pt.getActualTypeArguments()[0];
		if(Record.class.equals(modelClass)){
			return (T) getRecord();
		}else{
			return (T) super.getModel(modelClass);
		}
	}
	//@formatter:off 
	/**
	 * Title: getRecord
	 * Description:
	 * Created On: 2014年9月4日 下午3:40:01
	 * @author JiaYongChao
	 * <p>
	 * @return 
	 */
	//@formatter:on
	private Record getRecord() {
		Record rec = new Record();
		Map<String, String[]> parasMap = getRequest().getParameterMap();
		for (Entry<String, String[]> e : parasMap.entrySet()) {
			String paraKey = e.getKey();
			int pointIndex = paraKey.lastIndexOf(".");
			if(pointIndex > 0){
				paraKey = paraKey.substring(pointIndex+1);
			}
			String[] paraValue = e.getValue();
			try{
				if(StringUtils.isNotBlank(paraValue[0])){
					rec.set(paraKey, paraValue[0]);
				}
			} catch (Exception ex) {
				throw new RuntimeException("getRecord error!", ex);
			}
		}
		return rec;
	}
	/************************************		get 	set 	方法		************************************************/

	public Syslog getReqSysLog() {
		return reqSysLog;
	}

	public void setReqSysLog(Syslog reqSysLog) {
		this.reqSysLog = reqSysLog;
	}

}
